/********************************************
 * 功能说明: OrganizationEmployee实体对应的业务逻辑Service实现类
 * 模块名称:
 * 系统名称:
 * 软件版权: Frank
 * 系统版本: 1.0.0.1
 * 开发人员:
 * 开发时间: 2019-12-18 18:41:08
 * 审核人员:
 * 相关文档:
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.spring.arch.uaa.service;

import com.spring.arch.common.exception.ExceptionHolder;
import com.spring.arch.uaa.errorcode.UaaErrorCode;
import com.spring.arch.uaa.model.OrganizationEmployee;
import com.spring.arch.uaa.model.Project;
import com.spring.arch.uaa.model.TenantEmployee;
import com.spring.arch.uaa.model.User;
import com.spring.arch.common.exception.ExceptionHolder;
import com.spring.arch.uaa.model.OrganizationEmployee;
import com.spring.arch.uaa.model.Project;
import com.spring.arch.uaa.model.TenantEmployee;
import com.spring.arch.uaa.model.User;
import com.spring.arch.uaa.repository.OrganizationEmployeeRepository;
import com.spring.arch.uaa.repository.OrganizationEmployeeRoleRepository;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;

import static com.spring.arch.uaa.errorcode.UaaErrorCode.*;


/**
 * OrganizationEmployee实体对应的业务逻辑Service实现类
 *
 * @author
 * @version 1.0.0.1
 * @since 2019-12-18 18:41:08
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class OrganizationEmployeeService {

    @Autowired
    private OrganizationEmployeeRepository organizationEmployeeRepository;

    @Autowired
    private OrganizationEmployeeRoleRepository organizationEmployeeRoleRepository;

    @Autowired
    private UserService userService;

    public void save(OrganizationEmployee model) {

        Optional<OrganizationEmployee> optional =
                organizationEmployeeRepository.findByOrganizationAndEmployee(model.getOrganization(),
                        model.getEmployee());

        boolean flag = model.getId() == null && optional.isPresent()
                || model.getId() != null && optional.isPresent() && !Objects.equals(model.getId(), optional.get().getId());

        if(flag) {

            throw ExceptionHolder.serviceException(UaaErrorCode.E2001003002);
        }

        if(model.getUser() == null) {
            TenantEmployee tenantEmployee = model.getEmployee();
            User user = userService.createUser(tenantEmployee);
            model.setUser(user);
        }

        this.organizationEmployeeRepository.save(model);
    }


    public void saveAll(List<OrganizationEmployee> models) {

        models.forEach(model -> {

            Project project = model.getOrganization().getProject();
            if(project != null) {

                Optional<OrganizationEmployee> projectEmloyeeOptional = organizationEmployeeRepository
                        .findByOrganizationProjectAndEmployee(project, model.getEmployee());

                if(projectEmloyeeOptional.isPresent()) {

                    if(Objects.equals(projectEmloyeeOptional.get().getOrganization().getId(), project.getRootOrganization().getId())
                            && CollectionUtils.isEmpty(organizationEmployeeRoleRepository
                            .findByOrganizationEmployee(projectEmloyeeOptional.get()))) {

                        organizationEmployeeRepository.deleteById(projectEmloyeeOptional.get().getId());
                    } else {

                        throw ExceptionHolder.serviceException(UaaErrorCode.E2001002004);
                    }
                }

            }
            this.save(model);
        });
    }

    public void deleteById(UUID id) {

        // 查询要删除的对象
        OrganizationEmployee organizationEmployee = this.organizationEmployeeRepository.findById(id).orElseThrow(
                () -> ExceptionHolder.serviceException(UaaErrorCode.E2001004001, OrganizationEmployee.class.getSimpleName()));

        organizationEmployeeRoleRepository.deleteAllByOrganizationEmployee(organizationEmployee);
        // 查询租户人员
        TenantEmployee tenantEmployee = organizationEmployee.getEmployee();
        List<OrganizationEmployee> list = organizationEmployeeRepository.findByEmployeeId(tenantEmployee.getId());

        if(list.size() == 1) {

            // 没有在其它部门任职时，保存到根组织下
            organizationEmployee.setOrganization(organizationEmployee.getOrganization().getTenant().getRootOrganization());
            this.organizationEmployeeRepository.save(organizationEmployee);

        } else {

            // 在其它部门任职，删除这条数据
            this.organizationEmployeeRepository.deleteById(id);
        }
    }
}
